package com.atguigu.yygh.common.handler;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/8/21 18:39
 */
@Slf4j
@RestControllerAdvice // 标志是一个全局处理异常类
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class) // 粒度大
    public R handleException(Exception ex) {
        log.error(ex.getMessage());
        return R.error().message(ex.getMessage());
    }

    @ExceptionHandler(value = SQLException.class)
    public R handleSqlException(SQLException ex) {
        log.error(ex.getMessage());
        return R.error().message("sql异常");
    }

    @ExceptionHandler(value = ArithmeticException.class)
    public R handleArithmeticException(ArithmeticException ex) {
        log.error(ex.getMessage());
        return R.error().message("算数异常");
    }

    @ExceptionHandler(value = RuntimeException.class)
    public R handleRuntimeException(RuntimeException ex) {
        log.error(ex.getMessage());
        return R.error().message("运行期异常");
    }

    @ExceptionHandler(value = YyghException.class)
    public R handleYyghException(YyghException ex) {
        log.error(ex.getMessage());
        return R.error().code(ex.getCode()).message(ex.getMessage());
    }
}
